package com.myshiro.config;

import com.myshiro.pojo.SysUser;
import com.myshiro.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    SysUserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("获取<<身份信息/从token中取到账号和密码>>...............");
        //authenticationToken --> 从Controller 通过  subject.login(new AuthenticationToken("账号","密码"))
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        System.out.println("------------username: "+token.getUsername());

        //调用service验证账密
        SysUser sysUser = userService.login(token.getUsername());
        //char[] pwd=token.getPassword()

        if (null==sysUser) throw new UnknownAccountException("账户不存在");

        if (null==sysUser.getUsrFlag() || sysUser.getUsrFlag().intValue()==0)
            throw new LockedAccountException("账户被锁定");

        //principal
        SimpleAuthenticationInfo info =new SimpleAuthenticationInfo(sysUser
                                            ,sysUser.getUsrPassword() //把密码交给了shiro的Authentication去处理
                                            ,getName()
        );

        System.out.println("-------------realmName:  "+getName());//xxxx_0 代理的类

        return info;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("------获取<<权限信息>>...............");
        SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();//获取主体信息


        SimpleAuthorizationInfo zinfo =new SimpleAuthorizationInfo();

        //动态授权
        //① zinfo.addRole("管理员")  --> 得到当前登录用户的角色
        //② zinfo.addStringPermission("user:add");   --> 根据当前的角色信息,去获取该角色下拥有的权限列表


        //静态授权
        //模拟数据库中的数据
        //登录的时候查的是user表的全部数据 ,只有usr_id  role_id 没有roleName

        zinfo.addRole("管理员");
        zinfo.addStringPermission("user:list"); //所有的人都可以看列表

        System.out.println("--------------sysUser.getUsrRoleId():   "+sysUser.getUsrRoleId());

        if (1==sysUser.getUsrRoleId()){ //管理员
            zinfo.addStringPermission("user:add");
            zinfo.addStringPermission("user:update");
        }else{  //非管理员
            zinfo.addStringPermission("L0501");
        }


        return zinfo;
    }


}
